// stores/system.js - 系统状态管理
import { defineStore } from 'pinia'
import kvService from '../api/api_service'

export const useSystemStore = defineStore('system', {
  state: () => ({
    // 系统状态
    isOnline: true,
    lastHealthCheck: null,
    
    // 统计信息
    statistics: {
      cacheStats: null,
      idGeneratorStats: null,
      systemStats: null
    },
    
    // 性能数据
    performanceMetrics: {
      requestCount: 0,
      averageLatency: 0,
      errorRate: 0
    }
  }),

  getters: {
    systemHealth: (state) => ({
      online: state.isOnline,
      lastCheck: state.lastHealthCheck,
      uptime: state.statistics.systemStats?.upTimeSeconds || 0
    }),

    cacheHitRate: (state) => {
      return state.statistics.cacheStats?.hitRate || 0
    },

    memoryUsage: (state) => {
      const stats = state.statistics.systemStats
      if (!stats) return 0
      return (stats.usedMemoryMB / stats.totalMemoryMB) * 100
    }
  },

  actions: {
    async checkHealth() {
      try {
        await kvService.healthCheck()
        this.isOnline = true
        this.lastHealthCheck = new Date()
      } catch (error) {
        this.isOnline = false
        throw error
      }
    },

    async loadStatistics() {
      try {
        const stats = await kvService.getStatistics()
        this.statistics = {
          cacheStats: stats.cacheStats,
          idGeneratorStats: stats.idGeneratorStats,
          systemStats: stats.systemStats
        }
      } catch (error) {
        console.error('加载统计信息失败:', error)
        throw error
      }
    },

    updatePerformanceMetrics(latency, success = true) {
      this.performanceMetrics.requestCount++
      
      // 计算平均延迟
      const totalLatency = this.performanceMetrics.averageLatency * (this.performanceMetrics.requestCount - 1) + latency
      this.performanceMetrics.averageLatency = totalLatency / this.performanceMetrics.requestCount
      
      // 计算错误率
      if (!success) {
        this.performanceMetrics.errorRate = (this.performanceMetrics.errorRate * (this.performanceMetrics.requestCount - 1) + 100) / this.performanceMetrics.requestCount
      } else {
        this.performanceMetrics.errorRate = (this.performanceMetrics.errorRate * (this.performanceMetrics.requestCount - 1)) / this.performanceMetrics.requestCount
      }
    }
  }
})

// stores/kv.js - KV数据状态管理
export const useKvStore = defineStore('kv', {
  state: () => ({
    // KV数据
    kvPairs: new Map(),
    
    // 热点数据
    hotKeys: [],
    
    // 批量操作状态
    batchOperation: {
      isLoading: false,
      progress: 0,
      results: []
    },
    
    // 搜索和过滤
    searchTerm: '',
    filterOptions: {
      showOnlyExisted: false,
      sortBy: 'key', // key, id, accessCount, createdAt
      sortOrder: 'asc' // asc, desc
    }
  }),

  getters: {
    filteredKvPairs: (state) => {
      let pairs = Array.from(state.kvPairs.values())
      
      // 搜索过滤
      if (state.searchTerm) {
        pairs = pairs.filter(pair => 
          pair.key.toLowerCase().includes(state.searchTerm.toLowerCase()) ||
          (pair.value && pair.value.toLowerCase().includes(state.searchTerm.toLowerCase()))
        )
      }
      
      // 存在性过滤
      if (state.filterOptions.showOnlyExisted) {
        pairs = pairs.filter(pair => pair.existed)
      }
      
      // 排序
      pairs.sort((a, b) => {
        const { sortBy, sortOrder } = state.filterOptions
        let aVal = a[sortBy]
        let bVal = b[sortBy]
        
        if (typeof aVal === 'string') {
          aVal = aVal.toLowerCase()
          bVal = bVal.toLowerCase()
        }
        
        let result = 0
        if (aVal < bVal) result = -1
        else if (aVal > bVal) result = 1
        
        return sortOrder === 'desc' ? -result : result
      })
      
      return pairs
    },

    kvPairCount: (state) => state.kvPairs.size,
    
    batchProgress: (state) => state.batchOperation.progress
  },

  actions: {
    async getOrCreateKv(key, defaultValue = null) {
      try {
        const result = await kvService.getOrCreate(key, defaultValue)
        this.kvPairs.set(key, result)
        return result
      } catch (error) {
        console.error('获取或创建KV失败:', error)
        throw error
      }
    },

    async updateKv(key, value) {
      try {
        const result = await kvService.update(key, value)
        this.kvPairs.set(key, result)
        return result
      } catch (error) {
        console.error('更新KV失败:', error)
        throw error
      }
    },

    async deleteKv(key) {
      try {
        const success = await kvService.delete(key)
        if (success) {
          this.kvPairs.delete(key)
        }
        return success
      } catch (error) {
        console.error('删除KV失败:', error)
        throw error
      }
    },

    async batchGetOrCreate(keys) {
      this.batchOperation.isLoading = true
      this.batchOperation.progress = 0
      
      try {
        const result = await kvService.batchGetOrCreate(keys)
        
        // 更新本地缓存
        result.results.forEach(kvPair => {
          this.kvPairs.set(kvPair.key, kvPair)
        })
        
        this.batchOperation.results = result
        this.batchOperation.progress = 100
        
        return result
      } catch (error) {
        console.error('批量操作失败:', error)
        throw error
      } finally {
        this.batchOperation.isLoading = false
      }
    },

    async loadHotKeys(limit = 10) {
      try {
        this.hotKeys = await kvService.getHotKeys(limit)
      } catch (error) {
        console.error('加载热点数据失败:', error)
        throw error
      }
    },

    async warmUpCache(keys) {
      try {
        await kvService.warmUpCache(keys)
      } catch (error) {
        console.error('缓存预热失败:', error)
        throw error
      }
    },

    async clearCache() {
      try {
        await kvService.clearCache()
        // 清理本地缓存
        this.kvPairs.clear()
      } catch (error) {
        console.error('清理缓存失败:', error)
        throw error
      }
    },

    // 本地状态管理
    setSearchTerm(term) {
      this.searchTerm = term
    },

    setFilterOptions(options) {
      this.filterOptions = { ...this.filterOptions, ...options }
    },

    clearLocalData() {
      this.kvPairs.clear()
      this.hotKeys = []
      this.searchTerm = ''
    },

    // Group By 查询功能
    async groupByValue(pattern) {
      try {
        const result = await kvService.groupByValue(pattern)
        return result
      } catch (error) {
        console.error('按值分组查询失败:', error)
        throw error
      }
    },

    async groupByDate(startDate, endDate) {
      try {
        const result = await kvService.groupByDate(startDate, endDate)
        return result
      } catch (error) {
        console.error('按日期分组查询失败:', error)
        throw error
      }
    },

    async groupByDateAndValue(pattern, startDate, endDate) {
      try {
        const result = await kvService.groupByDateAndValue(pattern, startDate, endDate)
        return result
      } catch (error) {
        console.error('按日期和值分组查询失败:', error)
        throw error
      }
    },

    async searchByValue(pattern) {
      try {
        const result = await kvService.searchByValue(pattern)
        // 更新本地存储
        result.forEach(kvPair => {
          this.kvPairs.set(kvPair.key, kvPair)
        })
        return result
      } catch (error) {
        console.error('按值查询失败:', error)
        throw error
      }
    }
  }
})